package com.web.kdl.component;

import com.web.kdl.controller.send.Send;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.util.stereotypes.Lazy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ScheduledFuture;

@Component
@Slf4j
public class ReadDeviceDataTask {

    private final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    private ScheduledFuture<?> future;
    @PostConstruct
    public void init() {
        scheduler.initialize();
        start(); // 容器启动时自动启动任务
    }

    // 获取当前间隔
    @Getter
    private long interval = 30000; // 默认30秒
    @Autowired
    @Lazy
    private Send send;


    // 启动任务
    public void start() {
        stop(); // 如果已有任务，先停止
        future = scheduler.scheduleAtFixedRate(this::runTask, interval);
        log.info("任务已启动，间隔：{}ms", interval);
    }

    // 停止任务
    public void stop() {
        if (future != null && !future.isCancelled()) {
            future.cancel(false);
            log.info("任务已停止");
        }
    }

    // 修改间隔
    public void updateInterval(long newInterval, boolean restart) {
        this.interval = newInterval;
        if(restart){
            start(); // 停止并重启任务
        }
        log.info("任务间隔已修改为：{}ms", interval);
    }

    // 任务逻辑
    private void runTask() {
        send.execute();
    }

    // ---------- 新增方法 ----------
    // 判断任务是否运行中
    public boolean isRunning() {
        return future != null && !future.isCancelled();
    }

}
